﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="RelayCommand.cs" company="">
//   
// </copyright>
// <summary>
//   The relay command.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace TinyRadio.UserInterface.Infrastructure
{
    using System;
    using System.Diagnostics;
    using System.Windows.Input;

    /// <summary>The relay command.</summary>
    public class RelayCommand : ICommand
    {
        #region Fields

        /// <summary>The _can execute.</summary>
        private readonly Predicate<object> _canExecute;

        /// <summary>The _execute.</summary>
        private readonly Action<object> _execute;

        #endregion

        #region Constructors and Destructors

        /// <summary>Initializes a new instance of the <see cref="RelayCommand"/> class.</summary>
        /// <param name="execute">The execute.</param>
        public RelayCommand(Action<object> execute)
            : this(execute, null)
        {
        }

        /// <summary>Initializes a new instance of the <see cref="RelayCommand"/> class.</summary>
        /// <param name="execute">The execute.</param>
        /// <param name="canExecute">The can execute.</param>
        /// <exception cref="ArgumentNullException"></exception>
        public RelayCommand(Action<object> execute, Predicate<object> canExecute)
        {
            if (execute == null)
            {
                throw new ArgumentNullException("execute");
            }

            this._execute = execute;
            this._canExecute = canExecute;
        }

        #endregion

        #region Public Events

        /// <summary>The can execute changed.</summary>
        public event EventHandler CanExecuteChanged
        {
            add
            {
                CommandManager.RequerySuggested += value;
            }

            remove
            {
                CommandManager.RequerySuggested -= value;
            }
        }

        #endregion

        #region Public Methods and Operators

        /// <summary>The can execute.</summary>
        /// <param name="parameter">The parameter.</param>
        /// <returns>The <see cref="bool"/>.</returns>
        [DebuggerStepThrough]
        public bool CanExecute(object parameter)
        {
            return this._canExecute == null || this._canExecute(parameter);
        }

        /// <summary>The execute.</summary>
        /// <param name="parameter">The parameter.</param>
        public void Execute(object parameter)
        {
            this._execute(parameter);
        }

        #endregion
    }
}